package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.constant.EsConstant;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestPm;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;


@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult<HotelDoc> getPageAndTotal(RequestPm requestPm) {

        PageResult<HotelDoc> result = null;
        try {
            String sortBy = requestPm.getSortBy();
            String location = requestPm.getLocation();
            Integer page = requestPm.getPage();
            Integer size = requestPm.getSize();

            //创建请求
            SearchRequest searchRequest = new SearchRequest(EsConstant.INDEX);
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //查符合用户搜索条件的doc
            boolQueryMethod(requestPm, searchRequest, boolQuery);
            //todo 设置高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("name");
            highlightBuilder.requireFieldMatch(false);
            searchRequest.source().highlighter(highlightBuilder);
            //添加请求参数

            //距离条件
            if (location != null && !"".equals(location)) {
                searchRequest.source().sort(SortBuilders
                        .geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS)
                );

            }
            //分页
            searchRequest.source().from((page - 1) * size).size(size);

            //添加查询时增加分数展示条件
            FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQuery,
                    new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                            // 其中的一个function score 元素
                            new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                    // 过滤条件
                                    QueryBuilders.termQuery("isAD", true),
                                    ScoreFunctionBuilders.weightFactorFunction(20))
                    });
            searchRequest.source().query(functionScoreQuery);
            //排序
            sort(sortBy, searchRequest);
            //发送请求
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            //解析响应结果
            result = getHotelDocPageResult(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public Map<String, List<String>> filter(RequestPm requestPm) {


        try {
            SearchRequest searchRequest = new SearchRequest(EsConstant.INDEX);

            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            boolQueryMethod(requestPm, searchRequest, boolQuery);

            aggs(searchRequest, "brandAgg", "brand");
            aggs(searchRequest, "cityAgg", "city");
            aggs(searchRequest, "starNameAgg", "starName");

            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

            HashMap<String, List<String>> stringListMap = new HashMap<>();

            List<String> brandAggList = getStringListMap(response, "brandAgg");
            stringListMap.put("brand", brandAggList);
            List<String> cityAggList = getStringListMap(response, "cityAgg");
            stringListMap.put("city", cityAggList);
            List<String> starNameAggList = getStringListMap(response, "starNameAgg");
            stringListMap.put("starName", starNameAggList);

            return stringListMap;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new HashMap<>();
    }

    @Override
    public List<String> suggestion(String prefix) {

        try {
            SearchRequest request = new SearchRequest(EsConstant.INDEX);

            request.source().suggest(new SuggestBuilder().addSuggestion("suggestions",
                            SuggestBuilders.completionSuggestion("suggestion")
                                    .prefix(prefix)
                                    .skipDuplicates(true)
                                    .size(10)
                    )
            );

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestion = suggest.getSuggestion("suggestions");
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    //mq修改了酒店数据后，同步修改es数据
    @Override
    public void InsertByIdHotel(Long id) {
        try {
            Hotel byId = this.getById(id);
            HotelDoc hotelDoc = new HotelDoc(byId);
            //创建请求
            IndexRequest request = new IndexRequest("hotel").id(byId.getId().toString());
            //设置条件,需要设置id
            request.id(String.valueOf(id));
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            //发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //mq删除了酒店数据后，同步修改es数据
    @Override
    public void deleteByIdHotel(Long id) {
        try {

            //创建请求
            DeleteRequest delete = new DeleteRequest("hotel",id.toString());
            //发送请求
            client.delete(delete, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //
    private List<String> getStringListMap(SearchResponse response, String aggsName) {
        List<String> list = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        Terms brandAgg = aggregations.get(aggsName);
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            list.add(keyAsString);
        }
        return list;
    }

    //聚合查询
    private void aggs(SearchRequest searchRequest, String aggsName, String aggsField) {
        searchRequest.source()
                .size(0)
                .aggregation(AggregationBuilders.terms(aggsName)
                        .field(aggsField)
                        .size(10)
                );
    }

    //排序
    private void sort(String sortBy, SearchRequest searchRequest) {
        if ("score".equals(sortBy)) {
            searchRequest.source().sort("score", SortOrder.DESC);
        } else if ("price".equals(sortBy)) {
            searchRequest.source().sort("price", SortOrder.DESC);
        }
    }

    //响应解析
    private PageResult<HotelDoc> getHotelDocPageResult(SearchResponse response) {
        long value = response.getHits().getTotalHits().value;
        SearchHit[] hits = response.getHits().getHits();
        List<HotelDoc> hotelDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
            //解析高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields!=null && highlightFields.size()>0){
                HighlightField HighlightFieldName = highlightFields.get("name");
                String name = HighlightFieldName.getFragments()[0].toString();
                hotelDoc.setName(name);
            }
            //获取具体距离值
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                hotelDoc.setDistance(sortValues[0]);
            }

            hotelDocs.add(hotelDoc);
        }
        return new PageResult<>(hotelDocs, value);
    }

    //通过搜索查   和  设置条件查询
    private void boolQueryMethod(RequestPm requestPm, SearchRequest searchRequest, BoolQueryBuilder boolQuery) {

        String key = requestPm.getKey();
        String brand = requestPm.getBrand();
        String city = requestPm.getCity();
        String starName = requestPm.getStarName();
        Integer maxPrice = requestPm.getMaxPrice();
        Integer minPrice = requestPm.getMinPrice();

        if (key != null && !"".equals(key)) {
            boolQuery.must(QueryBuilders.matchQuery("all", key));

        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        //查询brand，city，星级，价格区间的条件
        if (brand != null && !"".equals(brand)) {
            boolQuery.must(QueryBuilders.termQuery("brand", brand));
        }
        if (city != null && !"".equals(city)) {
            boolQuery.must(QueryBuilders.termQuery("city", city));
        }
        if (starName != null && !"".equals(starName)) {
            boolQuery.must(QueryBuilders.termQuery("starName", starName));
        }
        if (maxPrice != null && minPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        }
        searchRequest.source().query(boolQuery);
    }


}